<!-- Page de détails d'un sous-domaine -->
<template>
  <div>
    <LayoutCommonSection>
      <UiLoadingPanel v-if="status == 'pending'" />
      <div v-else-if="subdomain !== null">
        <div>{{ $t('youRegisteredTheFollowingSubdomain') }} :</div>

        <div class="pa-8">
          <b>{{ subdomain.subdomain }}</b>
          <span class="text-on-neutral">.opentalent.fr</span>
        </div>

        <div>
          <div v-if="subdomain.active">
            <v-icon class="text-success icon small mr-2">
              fa-solid fa-check
            </v-icon>
            {{ $t('subdomainIsCurrentlyActive') }}
          </div>
          <div v-else>{{ $t('doYouWantToActivateThisSubdomain') }} ?</div>
        </div>

        <div class="mt-6 d-flex flex-row">
          <v-btn class="mr-12" @click="quit">
            {{ $t('back') }}
          </v-btn>
          <div v-if="!subdomain.active">
            <v-btn color="primary" @click="activateAndQuit">
              {{ $t('activate') }}
            </v-btn>
          </div>
        </div>
      </div>
    </LayoutCommonSection>
  </div>
</template>

<script setup lang="ts">
import type { Ref } from 'vue'
import Subdomain from '~/models/Organization/Subdomain'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import { useEntityManager } from '~/composables/data/useEntityManager'
import { usePageStore } from '~/stores/page'
import { TYPE_ALERT } from '~/types/enum/enums'
import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
import { useRouteUtils } from '~/composables/utils/useRouteUtils'

definePageMeta({
  name: 'activate_a_subdomain',
})

const { em } = useEntityManager()
const { fetch } = useEntityFetch()

const router = useRouter()

const { refreshProfile } = useRefreshProfile()

const { getIdFromRoute } = useRouteUtils()

const id = getIdFromRoute()

const { data: subdomain, status } = fetch(Subdomain, id)

const activationPending: Ref<boolean> = ref(false)

const pageStore = usePageStore()

const activateAndQuit = async () => {
  activationPending.value = true
  pageStore.loading = true
  await em.patch(Subdomain, id, { active: true })
  await refreshProfile()
  usePageStore().addAlert(TYPE_ALERT.SUCCESS, [
    'subdomain_activated_and_available_in_a_few_minutes',
  ])
  quit()
}

const quit = () => {
  router.push('/parameters/website')
  activationPending.value = false
  pageStore.loading = false
}

onUnmounted(() => {
  useRepo(Subdomain).flush()
})
</script>
